import React, { useState,useEffect } from 'react';
import { SafetyOutlined, MobileOutlined } from '@ant-design/icons';
import { Button, Form, Input } from 'antd';
import { useHistory } from 'react-router-dom';
import backgroundImage from '../assets/images/1.jpg';
import axios from 'axios';
import { Carousel } from 'react-responsive-carousel';
import logo1 from '../assets/images/2.jpg';
import logo2 from '../assets/images/3.jpg';
import logo3 from '../assets/images/4.jpg';
import logo4 from '../assets/images/5.jpg';
import logo5 from '../assets/images/6.jpg';
import logo6 from '../assets/images/7.jpg';

const Sms = () => {
  const [phone ,setPhone] = useState('');
  const [verifyMsg,setverifyMsg] = useState(''); 
  const [countdown, setCountdown] = useState(0);

  //使用useState定义一个名为formValid的state变量，并将初始值设为false
  const [formValid, setFormValid] = useState(false);
  const [form] = Form.useForm();
  //定义history，CLick,通过点击事件跳转到注册页面
  const history = useHistory();
  const RegisterClick = () => {
    history.push("/register");
  };
  //通过点击事件跳转到找回密码页面
  const PasswordClick = () => {
    history.push("/password");
  };
  //通过点击事件跳转到手机号登录页面
  const LoginClick = () => {
    history.push("/login");
  };
  // 通过点击事件跳转管理员登录页面
  const userClick = () =>{
    history.push("/admin");
  }
  // 点击登录跳转到首页
  const onClick1 = () => {
    form.validateFields().then(() => {
      if (formValid) {
        console.log('Login successful');
        // 点击登录跳转到首页
        // history.push("/");
      }
    });
  };
  // 点击发送手机验证码按钮，发送验证码
  const submitClick = () =>{
    axios.post('http://localhost:2023/auth/verifyMsg', {
      tel_number:phone,
      })
      .then((res) => {
        console.log(res);
      })
      .catch((error) => {
        console.log(error);
      });
      // 验证手机号码格式
    if (!/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(phone)) {
      return;
    }
    setCountdown(60);
  }
  //定义phone的数值进行输入判断，并提醒手机号是否正确，rule不可删除  
  const validatePhoneNumber = (rule, value) => {
    return new Promise((resolve, reject) => {
      if (!value) {
        reject('请输入手机号!');
      } else if (!/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(value)) {
        reject('手机号格式不正确!');
      } else {
        resolve();
      }
    });
  };  
  // 定义验证码，提示输入验证码，rule不可删除
  const validateCaptcha = (rule, value) => {
    return new Promise((resolve, reject) => {
      if (!value) {
        reject('请输入验证码!');
      } else {
        resolve();
      }
    });
  };
  // 定义一个禁用的按钮，手机号未输入不能点击发送验证码
  const disableButton = !phone || countdown > 0;
  // 设置定时器，进行倒计时显示
  useEffect(() => {
    if (countdown > 0) {
      const timer = setTimeout(() => {
        setCountdown(countdown - 1);
      }, 1000);
      return () => clearTimeout(timer);
    }
  }, [countdown]);

  // 轮播图
  const [currentSlide, setCurrentSlide] = useState(0);
  // 增加或减少当前幻灯片的函数
  const nextSlide = () => {
    setCurrentSlide((prevSlide) => (prevSlide === totalSlides - 1 ? 0 : prevSlide + 1));
  };
  const prevSlide = () => {
    setCurrentSlide((prevSlide) => (prevSlide === 0 ? totalSlides - 1 : prevSlide - 1));
  };
  const totalSlides = 6; // 假设有6张图片
  useEffect(() => {
    const interval = setInterval(() => {
      nextSlide();
    }, 2500);

    return () => {
      clearInterval(interval);
    };
  }, [currentSlide]);

  //点击登录
  const onFinish = () => {
    setFormValid(true);
    axios.post('http://localhost:2023/auth/v-login', {
      phone:phone, 
      verifyMsg:verifyMsg
    })
    .then((res)=>{
        console.log(res);
        history.push("/");
    }).catch(error => {
      console.error(error);
    });
  };

  return (
    <div style={{ 
      display: 'flex', 
      justifyContent: 'center', 
      height: '97vh', 
      alignItems: 'center',
      backgroundImage: `url(${backgroundImage})`,//背景图
      backgroundSize: 'cover',
      }}>
        {/* 轮播图 */}
       <div style={{ position: 'relative', maxWidth: '600px', margin: '0 auto',marginLeft:250 }}>
      <Carousel
        selectedItem={currentSlide}
        onChange={(index) => setCurrentSlide(index)}
        showThumbs={false}
        autoPlay={false}
        infiniteLoop={true}
        showArrows={false}
        showStatus={false}
        showIndicators={false}
      >     
          <img src={logo1} alt="Image 1" style={{ width: 650, height: 440, borderRadius: '10px 0 0 10px' }} />
          <img src={logo2} alt="Image 2" style={{ width: 650, height: 440, borderRadius: '10px 0 0 10px' }} />
          <img src={logo3} alt="Image 3" style={{ width: 650, height: 440, borderRadius: '10px 0 0 10px' }} />
          <img src={logo4} alt="Image 4" style={{ width: 650, height: 440, borderRadius: '10px 0 0 10px' }} />
          <img src={logo5} alt="Image 5" style={{ width: 650, height: 440, borderRadius: '10px 0 0 10px' }} />
          <img src={logo6} alt="Image 6" style={{ width: 650, height: 440, borderRadius: '10px 0 0 10px' }} />
      </Carousel>
      <div style={{ position: 'absolute', top: '50%', transform: 'translateY(-50%)', left: -15 }}>
        <Button onClick={prevSlide} type="link" style={{color: '#55CA92',fontSize:30}}>{"<"}</Button>
      </div>
      <div style={{ position: 'absolute', top: '50%', transform: 'translateY(-50%)', right: -15}}>
        <Button onClick={nextSlide} type="link" style={{color: '#55CA92',fontSize:30}}>{">"}</Button>
      </div>
    </div>
    {/* 表单 */}
      <div style={{ 
        border: '1px solid #BEBEBE',
        width: 300,
        padding: 20,
        borderRadius:'0 10px 10px 0',
        backgroundColor: 'rgba(255, 255, 255, 0)',
        boxShadow: '0 2px 4px rgba(0, 0, 0, 0.5)',
        marginRight:260,
        }}>
          {/* 登录标题 */}
        <h1 style={{ 
          textAlign: 'center',
          }}
          >
            登录
        </h1>
        <Form
          name="normal_login"
          className="login-form"
          initialValues={{
            remember: true,
          }}
          onFinish={onFinish}
        >
          {/* 手机号 */}
          <Form.Item
          name="phone"
          rules={[
            {
              required: true,
              validator: validatePhoneNumber,
            },
            ]}
            value={phone}
            onChange = {(e) => setPhone(e.target.value)}
          >
            <div style={{ 
              display: 'flex', 
              alignItems: 'center' 
              }}
            >
              <MobileOutlined className="icon" style={{ color: '#55CA92' }} />
              <Input 
              placeholder="手机号" 
              className="input" 
              style={{ 
                width: 250, 
                marginLeft: 20,
                backgroundColor: 'rgba(255, 255, 255, 0.3)' 
              }} 
              />
            </div>
          </Form.Item>
          {/* 验证码 */}
          <Form.Item
            name="captcha"
            rules={[
              {
                required: true,
                validator: validateCaptcha,
              },
            ]}
            value={verifyMsg}
            onChange = {(e) => setverifyMsg(e.target.value)}
          >
            <div style={{ 
              display: 'flex', 
              alignItems: 'center' 
              }}
            >
              <SafetyOutlined className="icon" style={{ color: '#55CA92' }} />
              <Input 
                type="text" 
                placeholder="验证码" 
                className="input" 
                style={{ 
                  width: 150, 
                  marginLeft: 20,
                  backgroundColor: 'rgba(255, 255, 255, 0.3)' 
                }} 
              />
              {/* 发送验证码按钮 */}
              <Button 
              style={{
                borderRadius:7,
                color:'white',
                backgroundColor:'#55CA92'
                }}
                onClick={submitClick}
                disabled={disableButton}
              >
                {countdown > 0 ? `${countdown}秒后重发` : '发送验证码'}
              </Button>
            </div>
          </Form.Item>
          {/* 立即注册、忘记密码 */}
          <Form.Item style={{ 
            display: 'flex', 
            justifyContent: 'space-between' 
            }}>
            <a href='' 
            style={{ 
              marginLeft: 15, 
              color: '#55CA92' 
              }} 
              onClick={RegisterClick}
            >
              立即注册
            </a>
            <a href=''
             style={{ 
              marginLeft:140, 
              color:'#55CA92' 
              }} 
              onClick={LoginClick}
            >
              用户名登录
            </a>
          </Form.Item>
          {/* 登录按钮 */}
          <Form.Item>
            <div 
            className="button-container" 
            style={{ 
              display: 'flex', 
              justifyContent: 'center' 
              }}>
              <Button 
              type="text" 
              htmlType="submit" 
              className="login-form-button" 
              onClick={onClick1 }
              style={{ 
                width: 200, 
                backgroundColor: '#55CA92', 
                color: 'white', 
                textAlign: 'center' 
                }}>
                登录
              </Button>
            </div>
          </Form.Item>
          <Form.Item style={{ 
            textAlign:'center', 
            }}>
            <a href='' 
            style={{ 
              marginLeft: 15, 
              color: '#55CA92' 
              }} 
              onClick={PasswordClick}
            >
              已有账号，忘记密码？
            </a>
          </Form.Item>
          <Button type="link" block style={{color: '#55CA92'}} onClick={userClick}>
            管理员登录
          </Button>
        </Form>
      </div>
    </div>
  );
};

export default Sms;